package org.burning.crm.workbench.web.controller;

import org.burning.crm.commons.constants.Constant;
import org.burning.crm.commons.domain.ReturnObject;
import org.burning.crm.commons.utils.SendMailUtils;
import org.burning.crm.settings.domain.DicValue;
import org.burning.crm.settings.domain.User;
import org.burning.crm.settings.service.SmsService;
import org.burning.crm.settings.service.UserService;
import org.burning.crm.workbench.domain.Contacts;
import org.burning.crm.workbench.service.ContactsService;
import org.burning.crm.workbench.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class SaleviewController {

    @Autowired
    private ContactsService contactsService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private UserService userService;

    @Autowired
    private org.burning.crm.settings.service.DicValueService dicValueService;

    @Autowired
    SmsService smsService;


//    @RequestMapping("/workbench/saleview/index.do")
//    public @ResponseBody
//    Object queryAllCustomerName(String customerName) {
//        String[] customerNames = customerService.queryCustomerNamesByName(customerName);
//
//        return customerNames;
//    }


    @RequestMapping("/workbench/saleview/sendphone.do")
    @ResponseBody
    public Object sendphone(@RequestParam("customerphone") String customerphone,@RequestParam("content") String content) {
        ReturnObject returnObject = new ReturnObject();
        System.out.println(content);
        System.out.println(customerphone);
//        boolean result = contactsService.sendphone(content,customerphone);
        boolean b = smsService.sendAll(customerphone, content);
        System.out.println(b);
        if (b) {
            returnObject.setCode(Constant.RETURN_OBJECT_CODE_SUCCESS);
            returnObject.setMessage("发送成功");
        } else {
            returnObject.setCode(Constant.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("发送失败");
        }
        returnObject.setCode(Constant.RETURN_OBJECT_CODE_SUCCESS);
        returnObject.setMessage("发送成功");
        return returnObject;
    }






    @RequestMapping("/workbench/saleview/index.do")
    public String index(HttpServletRequest request) {
        List<User> userList = userService.queryAllUsers();
        List<DicValue> sourceList = dicValueService.queryDicValueByTypeCode("source");
        List<DicValue> appellationList = dicValueService.queryDicValueByTypeCode("appellation");

        request.setAttribute("userList", userList);
        request.setAttribute("sourceList", sourceList);
        request.setAttribute("appellationList", appellationList);
        return "workbench/saleview/index";
    }


    @RequestMapping("/workbench/saleview/querySaleviewByConditionForPage.do")
    public @ResponseBody
    Object querySaleviewByConditionForPage(String owner, String fullname, String customerId, String customerphone,String customeremail, int pageNo, int pageSize) {
        Map<String, Object> map = new HashMap<>();

        map.put("owner", owner);
        map.put("fullname", fullname);
        map.put("customerId", customerId);
        map.put("customerphone", customerphone);
        map.put("customeremail", customeremail);
        map.put("beginNo", (pageNo - 1) * pageSize);
        map.put("pageSize", pageSize);


        List<Contacts> contactsList = contactsService.querySaleviewByConditionForPage(map);
        System.out.println(contactsList);
        System.out.println("==============================================");
        System.out.println("==============================================");
        int totalRows = contactsService.queryCountOfSaleviewByCondition(map);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("contactsList", contactsList);
        retMap.put("totalRows", totalRows);
        return retMap;
    }

    /**
     * 邮件群发
     * @param recipients    包含所有目标邮件的字符串
     * @param subject       邮件主题
     * @param content       发送内容
     * @return              响应信息对象
     */
    @RequestMapping("/saleview/sendEmailAll")
    @ResponseBody
    public Object sendEmailAll(
            @RequestParam("recipients")
            String recipients,
            @RequestParam
            String subject,
            @RequestParam
            String content) {
        ReturnObject returnObject = new ReturnObject();
        List<String> successList = new ArrayList<>();
        List<String> failList = new ArrayList<>();

        // 压缩的string保存到list，里面的元素就是每个邮箱
        List<String> emailList = Arrays.stream(recipients.split("\\s*,\\s*"))
                .map(String::trim)
                .filter(email -> !email.isEmpty())
                // 新增邮箱格式校验
                .filter(email -> email.matches("^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$"))
                .collect(Collectors.toList());

        // 如果邮箱全部都是无效的
        if (emailList.isEmpty()) {
            returnObject.setCode(Constant.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("无有效收件人地址");
            return returnObject;
        }

        // 遍历发送邮箱(管他什么屎山代码 干就完了)
        for (String email : emailList) {
            try {
                boolean sendResult = SendMailUtils.sendMail(email, subject, content);

                if (sendResult) {
                    successList.add(email);
                } else {
                    failList.add(email + "(发送失败)");
                }
            } catch (Exception e) {
                returnObject.setMessage(email + "(" + e.getMessage() + ")");
            }
        }

        if (!successList.isEmpty()) {
            returnObject.setCode(Constant.RETURN_OBJECT_CODE_SUCCESS);
            returnObject.setMessage("发送成功，数量：" + successList.size());
            returnObject.setRetData(successList);
            System.out.println(successList);
        } else {
            returnObject.setCode(Constant.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("发送失败");
            returnObject.setRetData(failList);
            System.out.println(failList);
        }

        return returnObject;
    }


}
